﻿Imports System.Windows.Data
Imports System.Windows.Controls
Imports Microsoft.Win32
Imports DelSole.VsiBuilder2010


Public Class VsiBuilderControl

    Dim itemsViewSource As CollectionViewSource
    Private contentsList As ItemsList
    Dim eula As String
    Dim addEula As Boolean = False

    Private Sub VsiBuilderControl_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

    End Sub

    Private Sub AddContentsButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim ofd As New Microsoft.Win32.OpenFileDialog

        With ofd
            .Multiselect = True
            .Title = "Select contents"
            .Filter = "All supported contents|*.addin;*.snippet;*.vssnippet|Code Snippets|*.snippet;*.vssnippet|Visual Studio add-ins|*.addin"
            If .ShowDialog = True Then
                For Each f In .FileNames
                    Dim i As New ItemFile(f)
                    If IO.Path.GetExtension(f).ToLower.Contains("snippet") Then
                        i.FileContentType = "Code Snippet"
                    Else
                        i.FileContentType = "Visual Studio add-in"

                        Dim ofdaddin As New OpenFileDialog
                        With ofdaddin
                            .Title = "Select the addin dll library"
                            .Filter = "Dll addin files|*.dll"
                            If .ShowDialog = True Then
                                i.Tag = .FileName
                            Else
                                Exit Sub
                            End If
                        End With
                    End If
                    Me.contentsList.Add(i)
                Next
            End If
        End With
    End Sub

    Private Sub CreatePackageButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        If Me.contentsList.Count = 0 Then
            Windows.MessageBox.Show("Add some contents first")
            Exit Sub
        End If
        Try
            Dim sfd As New Microsoft.Win32.SaveFileDialog
            With sfd
                .Title = "Specify the target .Vsi package name"
                .Filter = "Vsi Packages|*.vsi"
                If .ShowDialog = True Then
                    Dim v As New VsiPackage(Me.contentsList)
                    v.ContentInstallerVersion = "2.0"

                    If Me.eula <> "" And Me.addEula = True Then
                        v.Eula = Me.eula
                        v.CreatePackage(.FileName, addEula)
                    Else
                        v.CreatePackage(.FileName, False)
                    End If
                    System.Windows.MessageBox.Show("Package created successfully", "", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Information)
                    Exit Sub
                End If
            End With
        Catch ex As Exception

        End Try

    End Sub

    Private Sub EraseContentsButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        If Me.contentsList.Count = 0 Then Exit Sub
        Dim result = Windows.MessageBox.Show("Are you sure you want to remove all contents from the list?", "Vsi Builder 2010", Windows.MessageBoxButton.YesNo, Windows.MessageBoxImage.Question)
        If result = Windows.MessageBoxResult.Yes Then
            Me.contentsList.Clear()
        Else
            Exit Sub
        End If
    End Sub

    Private Sub RemoveSelectedButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        If Me.contentsList.Count = 0 Then Exit Sub
        Dim result = Windows.MessageBox.Show("Are you sure you want to remove the selected content from the list?", "Vsi Builder 2010", Windows.MessageBoxButton.YesNo, Windows.MessageBoxImage.Question)
        If result = Windows.MessageBoxResult.Yes Then
            Me.contentsList.Remove(CType(Me.ItemFileDataGrid.SelectedItem, ItemFile))
        Else
            Exit Sub
        End If
    End Sub

    Private Sub AddEulaButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim od As New Microsoft.Win32.OpenFileDialog
        With od
            .Title = "Select a text file as a license"
            .Filter = "Text files|*.txt|All Files|*.*"
            If .ShowDialog = True Then
                If String.IsNullOrEmpty(.FileName) = False Then
                    Try
                        Me.eula = My.Computer.FileSystem.ReadAllText(.FileName)
                    Catch ex As Exception
                        System.Windows.MessageBox.Show("The following error occurred:" & Environment.NewLine &
                                                      ex.Message, "", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
                        Exit Sub
                    End Try

                Else
                    Exit Sub
                End If
            End If
        End With
    End Sub

    Private Sub AddEulaCheck_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Me.addEula = CType(sender, CheckBox).IsChecked
    End Sub

    Private Sub DigitalSignatureButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim ofd As New Microsoft.Win32.OpenFileDialog

        With ofd
            .Title = "Select a .Vsi package"
            .Filter = ".Vsi packages|*.vsi"
            If .ShowDialog = True Then
                If String.IsNullOrEmpty(.Filter) = False Then
                    Try
                        Dim certFile As String = selectCertificate()
                        If certFile Is Nothing Then
                            System.Windows.MessageBox.Show("No certificate was selected.", "Vsi Builder 2010", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Exclamation)
                            Exit Sub
                        ElseIf IO.Path.GetExtension(certFile.ToLower) = ".pfx" Then
                            Dim pwdBox As New EnterPasswordWindow
                            pwdBox.ShowDialog()
                            If certificatePassword Is Nothing Then
                                System.Windows.MessageBox.Show("The password cannot be null")
                                Exit Sub
                            End If
                            VsiPackage.ApplyDigitalSignature(.FileName, certFile, certificatePassword)
                        Else
                            VsiPackage.ApplyDigitalSignature(.FileName, certFile, Nothing)
                        End If
                    Catch ex As Exception
                        System.Windows.MessageBox.Show("The following error occurred:" & Environment.NewLine &
                                                       ex.Message, "", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
                        Exit Sub
                    End Try

                End If
            Else
                Exit Sub
            End If
        End With
    End Sub

    Private Sub UninstallButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

        Dim un = ContentInstaller.ContentsToUninstall
        If un Is Nothing Then
            System.Windows.MessageBox.Show("Unable to load the history of installed items. Ensure at list one content was previously installed", "", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
            Exit Sub
        End If
        Me.ItemFileDataGrid.Visibility = Windows.Visibility.Hidden
        Me.MainStackPanel.Visibility = Windows.Visibility.Hidden
        Me.UninstallStackPanel.Visibility = Windows.Visibility.Visible
        Me.UninstallDataGrid.Visibility = Windows.Visibility.Visible
        Me.UninstallDataGrid.ItemsSource = un
    End Sub


    Private Sub UninstallSelectedButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim result = System.Windows.MessageBox.Show("Are you sure you want to uninstall the selected contents?", "Vsi Builder", Windows.MessageBoxButton.YesNo, Windows.MessageBoxImage.Question)

        If result = Windows.MessageBoxResult.No Then
            Exit Sub
        Else
            Try
                Dim items As New List(Of ContentToUninstall)
                For Each element In Me.UninstallDataGrid.SelectedItems
                    items.Add(CType(element, ContentToUninstall))
                Next

                If items.Any(Function(i) i.InstalledPath.ToLower.Contains(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86).ToLower) = True) Then
                    Dim adminCheck = System.Windows.MessageBox.Show("You are attempting to uninstall an element that is in the Program Files folder." & Environment.NewLine _
                                                                & "If you are running Visual Studio on Windows Vista/7, ensure the IDE is running with Administrator privileges before continuing" & Environment.NewLine _
                                                                & "Continue anyway?", "Vsi Builder 2010", Windows.MessageBoxButton.YesNo, Windows.MessageBoxImage.Question)

                    If adminCheck = Windows.MessageBoxResult.Yes Then
                        ContentInstaller.UninstallContents(items.AsEnumerable)
                        System.Windows.MessageBox.Show("Uninstall complete.")
                        Me.UninstallDataGrid.ItemsSource = ContentInstaller.ContentsToUninstall
                        Exit Sub
                    Else
                        Exit Sub
                    End If
                Else
                    ContentInstaller.UninstallContents(items.AsEnumerable)
                    System.Windows.MessageBox.Show("Uninstall complete.")
                    Me.UninstallDataGrid.ItemsSource = ContentInstaller.ContentsToUninstall
                End If


            Catch ex As Exception
                System.Windows.MessageBox.Show(ex.Message)
            End Try

        End If
    End Sub

    Private Sub ReturnToMainGridButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles ReturnToMainGridButton.Click
        Me.UninstallDataGrid.ItemsSource = Nothing
        Me.UninstallStackPanel.Visibility = Windows.Visibility.Hidden
        Me.UninstallDataGrid.Visibility = Windows.Visibility.Hidden
        Me.ItemFileDataGrid.Visibility = Windows.Visibility.Visible
        Me.MainStackPanel.Visibility = Windows.Visibility.Visible
    End Sub

    Private Sub HelpButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Process.Start("http://vsibuilder.codeplex.com")
    End Sub

    Private Function selectCertificate() As String
        Dim cd As New Microsoft.Win32.OpenFileDialog
        With cd
            .Title = "Select a certificate file"
            .Filter = "Spc certificates|*.spc|Pfx certificates|*.pfx|All files|*.*"
            If .ShowDialog = True Then
                Return .FileName
            Else
                Return Nothing
            End If
        End With
    End Function

    Private Sub SaveContentsListButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        If Me.ItemFileDataGrid.Items.Count = 0 Then
            System.Windows.MessageBox.Show("Please add any items before saving.", "Vsi Builder 2010", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Warning)
            Exit Sub
        End If

        Dim sd As New Microsoft.Win32.SaveFileDialog
        With sd
            .Title = "Select the file name for the export"
            .Filter = "Vsi Builder files|*.vsibuilder"
            If .ShowDialog = True Then
                Try
                    Me.contentsList.SaveToXml(.FileName)
                    System.Windows.MessageBox.Show("Export completed.", "Vsi Builder 2010", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Information)
                    Exit Sub
                Catch ex As Exception
                    System.Windows.MessageBox.Show(ex.Message)
                End Try
            End If
        End With
    End Sub

    Private Sub OpenContentsListButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim od As New Microsoft.Win32.OpenFileDialog
        With od
            .Title = "Select a contents list"
            .Filter = "Vsi Builder files|*.vsibuilder"
            If .ShowDialog = True Then
                Try
                    Me.contentsList.LoadFromXml(.FileName)
                    System.Windows.MessageBox.Show("Import completed.", "Vsi Builder 2010", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Information)
                    Exit Sub
                Catch ex As Exception
                    System.Windows.MessageBox.Show(ex.Message)
                End Try

            End If
        End With
    End Sub

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Me.itemsViewSource = CType(Me.FindResource("ItemFileViewSource"), CollectionViewSource)
        Me.contentsList = New ItemsList
        'Me.itemsViewSource.Source = contentsList
        Me.ItemFileDataGrid.ItemsSource = Me.contentsList

        If ContentInstaller.DotNet4SdkInstallDir = String.Empty Then
            System.Windows.MessageBox.Show("Windows SDK for Visual Studio 2010 not found. Digital signing feature will not be available.", "", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Information)
            Me.DigitalSignatureButton.IsEnabled = False
        End If
    End Sub
End Class
